export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const { address, location, type = 'regeo' } = query;
  
  // 高德地图API密钥
  const AMAP_KEY = 'ea14acfbeff3ab37b1a0ac893135a7e8';
  
  try {
    let geocodeData;
    
    if (type === 'regeo' && location) {
      // 逆地理编码：坐标转地址
      const response = await fetch(
        `https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_KEY}&location=${location}&output=json&extensions=all`
      );
      geocodeData = await response.json();
    } else if (type === 'geo' && address) {
      // 地理编码：地址转坐标
      const response = await fetch(
        `https://restapi.amap.com/v3/geocode/geo?key=${AMAP_KEY}&address=${encodeURIComponent(address as string)}&output=json`
      );
      geocodeData = await response.json();
    } else {
      throw createError({
        statusCode: 400,
        statusMessage: '缺少必要参数：location(逆地理编码) 或 address(地理编码)'
      });
    }
    
    if (geocodeData.status === '1') {
      return {
        success: true,
        data: geocodeData.regeocode || geocodeData.geocodes,
        message: '地理编码查询成功'
      };
    } else {
      throw createError({
        statusCode: 500,
        statusMessage: `地理编码API错误: ${geocodeData.info}`
      });
    }
  } catch (error) {
    console.error('地理编码API调用失败:', error);
    throw createError({
      statusCode: 500,
      statusMessage: '地理编码查询失败'
    });
  }
}); 